package com.yuanfeng.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.activity.dto.CommonIsXianUpdateDTO;
import com.yuanfeng.activity.dto.ReductionPolicyBaseAddDTO;
import com.yuanfeng.activity.dto.ReductionPolicyListQueryDTO;
import com.yuanfeng.activity.dto.ReductionPolicyRuleAddDTO;
import com.yuanfeng.activity.entity.ActivityReductionPolicyBaseEntity;
import com.yuanfeng.activity.entity.ActivityReductionPolicyGoodsEntity;
import com.yuanfeng.activity.entity.ActivityReductionPolicyRuleEntity;
import com.yuanfeng.activity.mapper.ActivityReductionPolicyBaseMapper;
import com.yuanfeng.activity.mapper.ActivityReductionPolicyGoodsMapper;
import com.yuanfeng.activity.mapper.ActivityReductionPolicyRuleMapper;
import com.yuanfeng.activity.service.ActivityReductionPolicyGoodsService;
import com.yuanfeng.activity.vo.ReductionPolicyGoodsDetailQueryVO;
import com.yuanfeng.activity.vo.ReductionPolicyListVO;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.GdsDetailsCommonQueryResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class ActivityReductionPolicyGoodsServiceImpl extends ServiceImpl<ActivityReductionPolicyGoodsMapper, ActivityReductionPolicyGoodsEntity>
    implements ActivityReductionPolicyGoodsService{
    @Resource
    private ActivityReductionPolicyBaseMapper activityReductionPolicyBaseMapper;
    @Resource
    private ActivityReductionPolicyRuleMapper activityReductionPolicyRuleMapper;
    @Override
    public ResponseResult invalidateManjianzengzheBase(Map<String, Object> param) {
        List<Integer> commonIds =this.baseMapper.selectList(new LambdaQueryWrapper<ActivityReductionPolicyGoodsEntity>()
                                 .eq(ActivityReductionPolicyGoodsEntity::getPromotionId,param.get("promotionId").toString()))
                                 .stream().map(ActivityReductionPolicyGoodsEntity::getCommonId).collect(Collectors.toList());
        param.put("updateTime", DateUtils.getNowDateToString());
        //活动状态:1-正常;0-已结束;2-管理员已关闭；4-平台失效
        param.put("promotionStatus",4);
        activityReductionPolicyBaseMapper.invalidManjianzengzheBase(param);
        if (null != commonIds && commonIds.size()>0) {
            List<Integer> commonList = commonIds;
            //活动删除，商品促销状态设为0
            Integer commonIsXian = 0 ;
            updateCommonIsXian(commonList,commonIsXian);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult deleteManjianzengzheBase(Map<String, Object> param) {
        List<Integer> commonIds =this.baseMapper.selectList(new LambdaQueryWrapper<ActivityReductionPolicyGoodsEntity>()
                .eq(ActivityReductionPolicyGoodsEntity::getPromotionId,param.get("promotionId").toString()))
                .stream().map(ActivityReductionPolicyGoodsEntity::getCommonId).collect(Collectors.toList());
        activityReductionPolicyBaseMapper.delete(new LambdaQueryWrapper<ActivityReductionPolicyBaseEntity>()
                                                .eq(ActivityReductionPolicyBaseEntity::getPromotionId,param.get("promotionId").toString()));
        activityReductionPolicyRuleMapper.delete(new LambdaQueryWrapper<ActivityReductionPolicyRuleEntity>()
                                                .eq(ActivityReductionPolicyRuleEntity::getPromotionId,param.get("promotionId").toString()));
        this.baseMapper.delete(new LambdaQueryWrapper<ActivityReductionPolicyGoodsEntity>()
                                               .eq(ActivityReductionPolicyGoodsEntity::getPromotionId,param.get("promotionId").toString()));
        // 查询参与此限时折扣的商品
        if (null != commonIds && commonIds.size()>0) {
            List<Integer> commonList = commonIds;
            //活动删除，商品促销状态设为0
            Integer commonIsXian = 0 ;
            updateCommonIsXian(commonList,commonIsXian);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryGoodsDetailList(Map<String, Object> param) {
        IPage<ReductionPolicyGoodsDetailQueryVO> page=this.baseMapper.queryGoodsDetailList(new Query<ReductionPolicyGoodsDetailQueryVO>().getPage(param),
                param);
        Integer activityType = activityReductionPolicyBaseMapper.selectById(param.get("promotionId").toString()).getPromotionStatus();//查询当前活动状态
        Map<String, Object> result=new HashMap<>();
        result.put("activityType",activityType);
        result.put("page",PageUtils.getPage(page));
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult queryReductionPolicyBaseList(Map<String, Object> param) {
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByTokenNoIsExist((String) param.get("token"));
        List<Integer> promotionIds = activityReductionPolicyRuleMapper.selectPromotionIds(param);
        if(0 == promotionIds.size()) {
            promotionIds.add(0);
        }
        if (userInfoVO != null){
            Integer shopId = Integer.valueOf(userInfoVO.getShopId());
            param.put("shopId",shopId);
        }
        param.put("promotionIds",promotionIds);
        IPage<ReductionPolicyListVO> page=activityReductionPolicyBaseMapper.selectManjianzengzheBaseList(new Query<ReductionPolicyListVO>().getPage(param),
                param);
        for(ReductionPolicyListVO baseResult: page.getRecords()){
            String rule = "[";
            Integer promotionId = baseResult.getPromotionId();
            ReductionPolicyListQueryDTO param1 = new ReductionPolicyListQueryDTO();
            param1.setPromotionId(promotionId);
            Integer hasGiveAway = activityReductionPolicyRuleMapper.selectCount(new LambdaQueryWrapper<ActivityReductionPolicyRuleEntity>()
                                                                    .eq(ActivityReductionPolicyRuleEntity::getPromotionId,promotionId)
                                                                    .eq(ActivityReductionPolicyRuleEntity::getHasGiveaway, CommonType.commonStatus.YES.getCode()));
            //查询规则
            List<String> ruleList = activityReductionPolicyRuleMapper.selectList(new LambdaQueryWrapper<ActivityReductionPolicyRuleEntity>()
                                   .eq(ActivityReductionPolicyRuleEntity::getPromotionId,param1.getPromotionId()))
                                   .stream().map(ActivityReductionPolicyRuleEntity::getPromotionContent).collect(Collectors.toList());
            if(null != ruleList && ruleList.size() > 0){
                baseResult.setPromotionContent(JSON.toJSONString(ruleList));
            }
            baseResult.setHasGiveaway(hasGiveAway);
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult deleteGoods(ReductionPolicyBaseAddDTO param) {
        if(null==param.getPromotionId()){
            return ResponseResult.success(BizCodeEnume.MISSING_PARAMETER);
        }
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions("", param.getToken());
        if (userPermissionsResult.getFlag()) {
            String shopId = userPermissionsResult.getShopId();
            param.setShopId(shopId);
            List<Integer> commonIds = param.getCommonIds();
            //遍历删除满减赠折商品表中相对应的活动商品
            if(null != commonIds && null != param.getPromotionId()) {
                for (Integer commonId : commonIds){
                   this.baseMapper.delete(new LambdaQueryWrapper<ActivityReductionPolicyGoodsEntity>()
                                  .eq(ActivityReductionPolicyGoodsEntity::getPromotionId,param.getPromotionId())
                                  .eq(ActivityReductionPolicyGoodsEntity::getShopId,shopId)
                                  .eq(ActivityReductionPolicyGoodsEntity::getCommonId,commonId));
                }
            }
            //更新商品促销状态
            //商品删除 商品是否参加促销状态修改为0
            updateCommonIsXian(commonIds,0);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(param.getCommonIds()+BizCodeEnume.DELETE_SUCCESS.getMsg());
    }

    @Override
    public ResponseResult addManjianzengzheBase(ReductionPolicyBaseAddDTO param) {
        List<Integer> commonList = new ArrayList<Integer>();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions("", param.getToken());
        if (userPermissionsResult.getFlag()) {
            String shopId = userPermissionsResult.getShopId();
            param.setShopId(shopId);
            // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
            Integer commonIsXian = 0;
            // 活动状态:1-正常;0-已结束;2-管理员已关闭  3 活动未开始
            Integer promotionStatus = 1;
            //当活动开始时间 大于 当前时间 活动以开始  否则活动未开始 通过定时任务修改活动、商品状态
            if (DateUtils.belongCalendar(new Date(), param.getStartTime(), param.getEndTime())) {
                promotionStatus = 1;
                commonIsXian = 5;
            } else {
                promotionStatus = 3;
                commonIsXian = 5;
            }
            // 商品状态是否正常
            ResponseResult rr = dealCommonIds(param);
            if(rr.getCode() == 1) {
                commonList = (List<Integer>) rr.getData();
            }else{
                return rr;
            }


            param.setPromotionStatus(promotionStatus);
            param.setUpdateTime(new Date());
            List<ReductionPolicyRuleAddDTO> discountRules = param.getDiscountRules();
            //如果新增则插入基础表否则修改基础表并清空规则表
            if (null == param.getPromotionId()) {
                param.setCreatedTime(new Date());
                this.baseMapper.insertManjianzengzheBase(param);
            }
            //遍历插入满减赠折规则表
            for (ReductionPolicyRuleAddDTO manjianzengzheRuleAddParam : discountRules) {
                manjianzengzheRuleAddParam.setPromotionId(param.getPromotionId());
                if(null == param.getPromotionId()) {
                    manjianzengzheRuleAddParam.setCreatedTime(new Date());
                }
                manjianzengzheRuleAddParam.setUpdateTime(new Date());
                //判断是否有赠品，设置标识
                if(null != manjianzengzheRuleAddParam.getGiveawayId() && manjianzengzheRuleAddParam.getGiveawayId() !=0){
                    manjianzengzheRuleAddParam.setHasGiveaway(1);
                }
                //生成活动内容
                dealPromotionContent(manjianzengzheRuleAddParam);
                activityReductionPolicyRuleMapper.insertManjianzengzheRules(manjianzengzheRuleAddParam);
            }
            List<Map<String, Integer>> goodsList = param.getGoodsList();
            //遍历插入满减赠折商品表
            if(null != goodsList&&null != param.getPromotionId()) {
                for (Map<String, Integer> goodsMap : goodsList){
                    ActivityReductionPolicyGoodsEntity manjianzengzheGoodsAddParam = new ActivityReductionPolicyGoodsEntity();
                    manjianzengzheGoodsAddParam.setPromotionId(param.getPromotionId());
                    manjianzengzheGoodsAddParam.setShopId(Integer.valueOf(shopId));
                    manjianzengzheGoodsAddParam.setGoodsId(goodsMap.get("goodsId"));
                    manjianzengzheGoodsAddParam.setCommonId(goodsMap.get("commonId"));
                    manjianzengzheGoodsAddParam.setCreatedTime(new Date());
                    manjianzengzheGoodsAddParam.setUpdateTime(new Date());
                    this.baseMapper.insert(manjianzengzheGoodsAddParam);


                }
            }

            //更新商品促销状态
            updateCommonIsXian(commonList,commonIsXian);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success( param.getCommonIds());
    }

    @Override
    public ResponseResult addGoods(ReductionPolicyBaseAddDTO param) {
        List<Integer> commonList = new ArrayList<Integer>();
        if(null==param.getPromotionId()){
            return ResponseResult.success(BizCodeEnume.MISSING_PARAMETER);
        }
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions("", param.getToken());
        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            ActivityReductionPolicyBaseEntity mjzzBaseInfo = activityReductionPolicyBaseMapper.selectById(param.getPromotionId());
            // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
            Integer commonIsXian = 0;
            // 判断活动是否已结束
            // 超出活动时间
            if (DateUtils.belongCalendar(new Date(), mjzzBaseInfo.getStartTime(), mjzzBaseInfo.getEndTime())) {
                commonIsXian = 5;
            } else {
                return ResponseResult.fail(0, "活动"+param.getPromotionId()+"已结束");
            }
            // 活动状态为非正常
            if(1!=mjzzBaseInfo.getPromotionStatus()){
                return ResponseResult.fail(0, "活动"+param.getPromotionId()+"已结束");
            }
            // 商品状态是否正常
            ResponseResult rr = dealCommonIds(param);
            if(rr.getCode() == 1) {
                commonList = (List<Integer>) rr.getData();
            }else{
                return rr;
            }
            List<Map<String, Integer>> goodsList = param.getGoodsList();
            //遍历插入满减赠折商品表
            if(null != goodsList&&null != param.getPromotionId()) {
                for (Map<String, Integer> goodsMap : goodsList){
                    ActivityReductionPolicyGoodsEntity manjianzengzheGoodsAddParam = new ActivityReductionPolicyGoodsEntity();
                    manjianzengzheGoodsAddParam.setPromotionId(param.getPromotionId());
                    manjianzengzheGoodsAddParam.setShopId(Integer.valueOf(userPermissionsResult.getShopId()));
                    manjianzengzheGoodsAddParam.setGoodsId(goodsMap.get("goodsId"));
                    manjianzengzheGoodsAddParam.setCommonId(goodsMap.get("commonId"));
                    manjianzengzheGoodsAddParam.setCreatedTime(new Date());
                    manjianzengzheGoodsAddParam.setUpdateTime(new Date());
                    this.baseMapper.insert(manjianzengzheGoodsAddParam);
                }
            }
            //更新商品促销状态
            updateCommonIsXian(commonList,commonIsXian);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success( commonList);
    }

    /**
     * 生成活动内容
     * 1. 若活动类型为满减,discountType=1:
     * 1.1 若hasGiveaway=0,无赠品:
     * 活动内容为:单笔满¥meetAmount，立减现金¥discountContent
     * 1.2 若hasGiveaway=1,有赠品:
     * 1.2.1 discountContent不为空:
     * 活动内容为:单笔满¥meetAmount，立减现金¥discountContent,送礼品giveawayName
     * 1.2.2 discountContent为空:
     * 活动内容为:单笔满¥meetAmount，送礼品giveawayName
     * 2. 若活动类型为满折,discountType=3:
     * 活动内容为:单笔订单满meetAmount件，立减折扣discountContent%
     *
     * @param manjianzengzheRuleAddParam
     * @return
     */
    private void dealPromotionContent(ReductionPolicyRuleAddDTO manjianzengzheRuleAddParam) {
        Integer discountType = manjianzengzheRuleAddParam.getDiscountType();
        BigDecimal meetAmount = manjianzengzheRuleAddParam.getMeetAmount();
        Integer hasGiveaway = manjianzengzheRuleAddParam.getHasGiveaway();
        String discountContent = manjianzengzheRuleAddParam.getDiscountContent();
        Integer giveawayId = manjianzengzheRuleAddParam.getGiveawayId();
        StringBuilder promotionContent = new StringBuilder();
        //满减赠活动
        if(null != discountType && 1 == discountType){
            //有赠品
            if(null !=hasGiveaway && 1 == hasGiveaway){
                GdsDetailsCommonQueryResultVO queryResult = this.baseMapper.selectByCommonId(giveawayId);
                String giveawayName = queryResult.getCommonName();
                //满减内容不为空
                //活动内容:单笔满¥meetAmount，立减现金¥discountContent,送礼品giveawayName
                if(null != discountContent && !"".equals(discountContent)){
                    promotionContent.append("单笔满¥");
                    promotionContent.append(meetAmount);
                    promotionContent.append("，立减现金¥");
                    promotionContent.append(discountContent);
                    promotionContent.append("，送礼品");
                    promotionContent.append(giveawayName);
                    //满减内容为空
                    //活动内容为:单笔满¥meetAmount，送礼品giveawayName
                }else{
                    promotionContent.append("单笔满¥");
                    promotionContent.append(meetAmount);
                    promotionContent.append("，送礼品");
                    promotionContent.append(giveawayName);
                }
                //无赠品
                //活动内容为:单笔满¥meetAmount，立减现金¥discountContent
            }else{
                promotionContent.append("单笔满¥");
                promotionContent.append(meetAmount);
                promotionContent.append("，立减现金¥");
                promotionContent.append(discountContent);
            }
            //满折活动
            //活动内容为:单笔订单满meetAmount件，立减折扣discountContent%
        }else if (null != discountType && 3 == discountType){
            promotionContent.append("单笔订单满");
            promotionContent.append(meetAmount);
            promotionContent.append("件，立享");
            promotionContent.append(discountContent);
            promotionContent.append("折");

        }
        manjianzengzheRuleAddParam.setPromotionContent(promotionContent.toString());

    }


    //查询商品状态是否正常
    private ResponseResult dealCommonIds(ReductionPolicyBaseAddDTO param) {
        List<Map<String, Integer>> goodsList = param.getGoodsList();
        List<Integer> commonList = new ArrayList<Integer>();
        if(null != goodsList) {
            for (Map<String, Integer> goodsMap : goodsList) {
                Integer commonId = goodsMap.get("commonId");
                if(null == commonId){
                    return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
                }
                commonList.add(commonId);
                Map<String, Object> goodsMessage = this.baseMapper.selectManjianzengzheMessage(commonId);
                if (null == goodsMessage) {
                    return  ResponseResult.fail(0, "商品不存在或下架，commonid=" + commonId);
                }
            }
        }

        return ResponseResult.success(commonList);

    }

    //更新商品促销状态
    private void updateCommonIsXian(List<Integer> commonList, Integer commonIsXian) {
        if (!CollectionUtils.isEmpty(commonList)) {
            CommonIsXianUpdateDTO commonIsXianUpdateParam = new CommonIsXianUpdateDTO();
            // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
            commonIsXianUpdateParam.setCommonIdList(commonList);
            commonIsXianUpdateParam.setCommonIsXian(commonIsXian);
            if (!CollectionUtils.isEmpty(commonList) && commonList.size() > 0) {
                activityReductionPolicyBaseMapper.updateCommonIsXian3(commonIsXianUpdateParam);
            }
        }
    }
}




